import React, { FC } from 'react';
import { record } from 'rrweb';
import Player from 'rrweb-player';
import 'rrweb-player/dist/style.css';

const events: any[] = [];
const RRWeb: FC = () => {
  const recordClick = () => {
    record({
      emit(evet, isCheckout) {
        if (isCheckout) {
          // 上报信息
          window.sessionStorage.setItem(
            'rr-web-events',
            JSON.stringify(events)
          );
          console.log('信息上报成功');
        }
        events.push(evet);
      },
      recordCanvas: true,
      checkoutEveryNms: 1000 * 3,
    });
  };

  const player = () => {
    const events = window.sessionStorage.getItem('rr-web-events');
    const root = document.getElementById('player-root');
    if (!root || !events) return;
    const replayer = new Player({
      target: root,
      props: {
        events: JSON.parse(events),
        height: 500,
      },
    });
    replayer.play();
  };

  return (
    <>
      <h1>RRWeb 使用</h1>
      <button onClick={recordClick}>开始录制</button>
      <button onClick={player}>回放</button>
      <h2>回放区域</h2>
      <div
        id="player-root"
        style={{
          width: '100%',
          height: '500px',
          border: '1px solid #000',
        }}
      ></div>
    </>
  );
};

export default RRWeb;
